package com.sky.controller.user;

import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "C端-菜品浏览接口")
public class DishUserController {

    @Autowired
    private DishService dishService;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishVO>> list(Long categoryId) {
        String CATEGORY_DISH_ID = "DISH_" + categoryId;
        // 获取到的就是一个集合
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(CATEGORY_DISH_ID);
        // 如果没有就创建,创建之后保存到redis,然后在返回
        if (list == null) {
            DishDTO dishDTO = new DishDTO();
            dishDTO.setCategoryId(categoryId);
            dishDTO.setStatus(StatusConstant.ENABLE);// 查询起售中的菜品
            list = dishService.listWithFlavor(dishDTO);
            redisTemplate.opsForValue().set(CATEGORY_DISH_ID,list, 30, TimeUnit.MINUTES);
            return Result.success(list);
        }
        // 如果有就直接返回
        return Result.success(list);
    }
}
